package gewu.suleju.aop;

import gewu.suleju.anno.FormToken;
import gewu.suleju.exception.FormTokenException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.UUID;

@Component
@Aspect
public class FormRepeatAop {
    @Autowired
    private RedisTemplate redisTemplate;

    @Before("within(@org.springframework.web.bind.annotation.RestController *) && @annotation(token)")
    public void aop(JoinPoint joinPoint, FormToken token){
        //获取注解的属性值
        if(token.save()){
            //生成一个token,放入到session/redis中
            String serverToken = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("formToken" ,serverToken);
        }
        if(token.repeat()) {
            //判断是否是重复提交
            //1. 判断redis中是否存在serverToken
            if(isRepeat(joinPoint)) {
                throw new FormTokenException("sorry!不能够重复提交!");
            }

            redisTemplate.delete("formToken");
        }

    }
    private boolean isRepeat(JoinPoint joinPoint){

        String serverToken = (String)redisTemplate.opsForValue().get("formToken");

        if(null==serverToken){
            return true;
        }
        //判断客户端隐藏域中传过来的token是否和serverToken一致
        String clientToken =  (String)joinPoint.getArgs()[0];
        if(clientToken==null || clientToken.trim().length()==0){
            return true;
        }

        if(!clientToken.equals(serverToken)){
            return true;
        }
        return false;
    }
}
